﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Management;

namespace NetStatistics
{
	[Serializable]
	public class NetworkAdapter
	{
		public NetworkAdapter(string adapterName)
		{
			this.name = adapterName;
		}

		private string name;
		public string Name
		{
			get { return name; }			
		}

		private long downloadSpeed;
		public double DownloadSpeed
		{
			get { return (double)downloadSpeed / 1024; }
		}

		private long uploadSpeed;
		public double UploadSpeed
		{
			get { return (double)uploadSpeed / 1024; }
		}

		private PerformanceCounter downloadedBytesCounter;
		public PerformanceCounter DownloadedBytesCounter
		{
			get { return downloadedBytesCounter; }
			set { downloadedBytesCounter = value; }
		}

		private PerformanceCounter uploadedBytesCounter;
		public PerformanceCounter UploadedBytesCounter
		{
			get { return uploadedBytesCounter; }
			set { uploadedBytesCounter = value; }
		}

		private long downloadedBytes;
		private long uploadedBytes;
		private long downloadedBytesOld;
		private long uploadedBytesOld;
		
		public void Refresh()
		{
			this.downloadedBytes = this.downloadedBytesCounter.NextSample().RawValue;
			this.uploadedBytes = this.uploadedBytesCounter.NextSample().RawValue;

			this.downloadSpeed = this.downloadedBytes - this.downloadedBytesOld;
			this.uploadSpeed = this.uploadedBytes - this.uploadedBytesOld;

			this.downloadedBytesOld = this.downloadedBytes;
			this.uploadedBytesOld = this.uploadedBytes;
		}

		public void Init()
		{
			this.downloadedBytesOld = this.downloadedBytesCounter.NextSample().RawValue;
			this.uploadedBytesOld = this.uploadedBytesCounter.NextSample().RawValue;
		}

		private bool enabled = true;
		public bool Enabled
		{
			get { return enabled; }			
		}

		public void Enable()
		{
			// Not implemented yet
		}

		public void Disable()
		{
			// Not implemented yet
		}

		public override string ToString()
		{
			return this.name;
		}

		public override bool Equals(object obj)
		{
			NetworkAdapter adapter = obj as NetworkAdapter;
			
			if (adapter == null)
				return false;

			return (this.Name == adapter.Name
				&& this.DownloadSpeed == adapter.DownloadSpeed
				&& this.UploadSpeed == adapter.UploadSpeed
				&& this.Enabled == adapter.Enabled);
		}
	}
}
